import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-project-config',
  templateUrl: './project-config.component.html'
})
export class ProjectConfigComponent implements OnInit {
  validatorOptions = {
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      putOffForDay: {
        validators: {
          notEmpty: {
            message: '请输入延迟天数'
          }
        }
      }
    }
  }
  tableData: any[] = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  tableSearch: any = {
    companyId: '',
    companyName: '',
    roleId: '',
    isOpenDocking: '',
    isOpenApi: ''
    //		searchKey: ''
  }
  startTime: string = ''
  endTime: string = ''
  apiList: any //用户数据
  interfaceKey: string = '' //接口ID
  interfaceName: string = '' //接口名称
  projectConfigFrom: any = {
    id: '',
    companyId: '',
    companyName: '',
    roleId: '',
    roleName: '',
    isOpenDocking: '1',
    isOpenApi: '1',
    isOpenRenewalApi: '1',
    renewalRecodeQueryRoleState: '0',
    describe: '',
    putOffForDay: '',
    maxExpirationDay: ''
  }
  paramFormat: any = {
    id: 'id',
    text: 'name'
  }
  dataURL: string = 'role/roleList.html'
  queryParam: any = {
    userType: '1'
  }
  roleList: any = [] // 存储角色数据
  formType: string = 'new'

  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }
  //公司[项目]选中回调
  companySelected(data) {
    this.tableSearch.companyId = data.companyId
    this.tableSearch.companyName = data.companyName
  }
  //公司[项目]选中回调
  companySelectedForm(data) {
    this.projectConfigFrom.companyId = data.companyId
    this.projectConfigFrom.companyName = data.companyName
  }
  //角色选中
  optionSelected(data) {
    this.tableSearch.roleId = data.id
    this.tableSearch.roleName = data.text
  }
  //角色选中
  optionSelectedForm(data) {
    this.projectConfigFrom.roleId = data.id
    this.projectConfigFrom.roleName = data.text
  }
  // 接收子组件传递过来的数据
  getSelectTableTime(time) {
    this.startTime = time.startTime
    this.endTime = time.endTime
  }
  ngOnInit() {
    this.load()
    this.getRoleList()
  }
  // 角色
  getRoleList() {
    this.jsonApiService.http_obj('role/roleList.html', { userType: '1' }).subscribe(data => {
      if (data.success) {
        this.roleList = data.data
      }
    })
  }
  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.load()
  }
  //初始化加载list数据
  load() {
    //		let timeCheck = common.correctTimeParams(this.startTime,this.endTime,0);
    //		if(!timeCheck.status){
    //			this.jsonApiService.message(timeCheck.message);
    //			return;
    //		}
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        companyId: this.tableSearch.companyId,
        roleId: this.tableSearch.roleId,
        isOpenDocking: this.tableSearch.isOpenDocking,
        isOpenApi: this.tableSearch.isOpenApi
        //searchKey: common.stringTrim(this.tableSearch.searchKey)
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('projectDocking/projectDockingConfigList.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  //删除
  delRow(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      this.jsonApiService
        .http_obj('projectDocking/delProjectDockingConfig.html', {
          id: row.id
        })
        .subscribe(data => {
          this.jsonApiService.message(data.message)
          if (data.success) {
            this.load()
          }
        })
    })
  }

  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  /*
   * 新增
   */
  table_add(modal) {
    this.modalClose(modal)
    modal.show()
    this.formType = 'new'
    $('.insert_text .help-block').text('请输入一个有效的数字')
  }
  /*
   * 启用项目车辆对接change回调
   */
  isOpenDockingChange(val) {
    this.projectConfigFrom.isOpenDocking = val
  }
  /*
   * API接口启用到期限制change回调
   */
  isOpenApiChange(val) {
    this.projectConfigFrom.isOpenApi = val
  }
  /*
   * 是否开始第三方接口续费操作change回调
   */
  isOpenRenewalApiChange(val) {
    this.projectConfigFrom.isOpenRenewalApi = val
  }
  /*
   * 是否开放续费记录
   */
  isOpenRenewalRecordChange(val) {
    this.projectConfigFrom.renewalRecodeQueryRoleState = val
  }
  /**
   * 
   * 校验到期天数
   */
  changeMaxExpirationDay(val) {
    console.log(val)
    const reg = /^[1-9]\d*$/;
    if (val && !reg.test(val)) {
      this.jsonApiService.message('请输入正整数')
      this.projectConfigFrom.maxExpirationDay = null
      return
    }
  }
  /*
   * 编辑
   */
  editRow(row, modal) {
    modal.show()
    //		this.projectConfigFrom.id = row.id;
    this.formType = 'updata'
    for (let item in this.projectConfigFrom) {
      this.projectConfigFrom[item] = row[item]
      if (item == 'isOpenDocking' || item == 'isOpenApi' || item == 'isOpenRenewalApi' || item == 'renewalRecodeQueryRoleState') {
        this.projectConfigFrom[item] = row[item] + ''
      }
      if (item == 'isOpenRenewalApi' || item == 'renewalRecodeQueryRoleState') {
        if (row[item] == null) this.projectConfigFrom[item] = '0'
      }
    }
    $('#roleSelect2Form').val(row.roleId).trigger('change')
    /**
     *  非常规开发:  单独处理角色问题,在变更角色名称,角色ID没有发生变化,编辑的时候拉角色接口数据,更新到最新的角色名称覆盖旧的数据
     */
    for (let item of this.roleList) {
      if (item.id == row.roleId) {
        this.projectConfigFrom.roleName = item.name
      }
    }
  }

  /*
   * 关闭弹窗
   */
  modalClose(modal) {
    modal.hide()
    $('#projectConfigFrom').data('bootstrapValidator').resetForm()
    this.projectConfigFrom = {
      id: '',
      companyId: '',
      companyName: '',
      roleId: '',
      roleName: '',
      isOpenDocking: '1',
      isOpenApi: '1',
      isOpenRenewalApi: '1',
      renewalRecodeQueryRoleState: '0',
      describe: '',
      putOffForDay: 0,
      maxExpirationDay: null
    }
    //		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
    $('#roleSelect2Form').val('').trigger('change')
    //      $("#select2-"+this.select2ElementID+"-container").empty();
    //      $("#select2-"+this.select2ElementID+"-container").attr("title", "");
    //      $("#select2-"+this.select2ElementID+"-container").prepend(str);
  }
  /*
   * form提交
   */
  apiControlSubmit(modal) {
    $('#projectConfigFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#projectConfigFrom').data('bootstrapValidator').isValid() //验证是否通过
    let dataObj = this.projectConfigFrom
    if (isValid) {
      if (dataObj.maxExpirationDay == null || dataObj.isOpenRenewalApi == '0' || dataObj.maxExpirationDay == '') {
        delete dataObj.maxExpirationDay
      }
      this.jsonApiService
        .http_obj('projectDocking/editProjectDockingConfig.html', dataObj)
        .subscribe(data => {
          this.jsonApiService.message(data.message)
          if (data.success) {
            this.load()
            this.modalClose(modal)
          }
        })
    }
  }
}
